//
//  HLUserDetailInfoView.m
//  YueYue
//
//  Created by hulu001 on 2023/5/18.
//

#import "HLUserDetailInfoView.h"
#import <SDCycleScrollView/SDCycleScrollView.h>
#import "HLCycleScrollCell.h"
#import "HLEditNicknameViewController.h"
#import "HLPickerManager.h"
#import "HLUserOptionRequest.h"
#import "HLEditInfoRequest.h"

@interface HLUserDetailInfoView ()<SDCycleScrollViewDelegate>

@property (nonatomic, strong) SDCycleScrollView *cycleScrollView;
@property (nonatomic, strong) UIImageView *avatarView;
@property (nonatomic, strong) UITapGestureRecognizer *avatarTapGesture;
@property (nonatomic, strong) UILabel *nicknameLabel;
@property (nonatomic, strong) QMUIButton *editButton;
@property (nonatomic, strong) QMUIButton *sexView;
@property (nonatomic, strong) QMUIButton *idView;
@property (nonatomic, strong) QMUIButton *idCopyButton;
@property (nonatomic, strong) QMUIButton *followButton;
@property (nonatomic, strong) NSArray <HLOpusModel *> *cycleDatas;

@end

@implementation HLUserDetailInfoView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = UIColorWhite;
        [self setupView];
        
    }
    return self;
}

- (void)setupView
{
    
    self.cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0,SCREEN_WIDTH, 365) delegate:self placeholderImage:[HLUIHelper avatarBigPlaceholder]];
    _cycleScrollView.bannerImageViewContentMode = UIViewContentModeScaleAspectFill;
    [self addSubview:_cycleScrollView];
    [_cycleScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(0);
        make.height.mas_equalTo(365);
    }];
    
    CGFloat size = 64;
    self.avatarView = [[UIImageView alloc] init];
    _avatarView.image = [HLUIHelper avatarPlaceholder];
    _avatarView.contentMode = UIViewContentModeScaleAspectFit;
    [self addSubview:_avatarView];
    _avatarView.layer.masksToBounds = YES;
    _avatarView.layer.cornerRadius = size / 2;
    _avatarView.layer.borderWidth = 1;
    _avatarView.layer.borderColor = UIColorWhite.CGColor;
    _avatarView.userInteractionEnabled = YES;
    [_avatarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(size);
        make.left.mas_equalTo(12);
        make.top.equalTo(_cycleScrollView.mas_bottom).offset(16);
    }];
    
    self.avatarTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(avatarPreview)];
    [_avatarView addGestureRecognizer:_avatarTapGesture];
    
    self.nicknameLabel = [[UILabel alloc] init];
    _nicknameLabel.font = UIFontMediumMake(20);
    _nicknameLabel.textColor = UIColorBlack;
    _nicknameLabel.text = @"阿杂不堪";
    _nicknameLabel.numberOfLines = 3;
    [self addSubview:_nicknameLabel];
    [_nicknameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_avatarView.mas_right).offset(12);
        make.top.equalTo(_avatarView).offset(6);
        make.width.mas_lessThanOrEqualTo(SCREEN_WIDTH - 202);
    }];
    
    self.idView = [HLUIHelper iconIDViewWithId:@"12456"];
    [self addSubview:_idView];
    [_idView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_nicknameLabel);
        make.top.equalTo(_nicknameLabel.mas_bottom).offset(10);
        make.bottom.mas_equalTo(-16);
    }];

    
    self.idCopyButton = [[QMUIButton alloc] init];
    [_idCopyButton setImage:UIImageMake(@"user_detail_copy") forState:UIControlStateNormal];
    [_idCopyButton addTarget:self action:@selector(copyID) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_idCopyButton];
    [_idCopyButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_idView);
        make.left.equalTo(_idView.mas_right).offset(4);
    }];

    self.followButton = [[QMUIButton alloc] init];
    [_followButton setImage:UIImageMake(@"user_detail_follow") forState:UIControlStateNormal];
    [_followButton setTitle:@"关注" forState:UIControlStateNormal];
    [_followButton setTitleColor:HLMainColor forState:UIControlStateNormal];
    _followButton.titleLabel.font = UIFontMediumMake(13);
    _followButton.cornerRadius = 16;
    _followButton.layer.borderColor = HLMainColor.CGColor;
    _followButton.layer.borderWidth = 1.6;
    _followButton.contentEdgeInsets = UIEdgeInsetsMake(8, 10, 8, 10);
    _followButton.imagePosition = QMUIButtonImagePositionLeft;
    _followButton.spacingBetweenImageAndTitle = 4;
    [_followButton addTarget:self action:@selector(followAction) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_followButton];
    [_followButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_avatarView);
        make.right.mas_equalTo(-12);
    }];
}


- (void)setModel:(HLUserInfoModel *)model
{
    _model = model;
    BOOL isMe = [model.userId isEqualToString:[HLRunTime shareInstance].mine.userId];
    self.cycleScrollView.autoScroll = !isMe;
    [self.avatarView sd_setImageWithURL:[NSURL URLWithString:model.avatar] placeholderImage:HLUIHelper.avatarPlaceholder];
    [self.nicknameLabel setText:model.nickName];
    self.editButton.hidden = !isMe;
    self.followButton.hidden = isMe;
    [self.idView setTitle:[NSString stringWithFormat:@"ID: %@", model.userYueId] forState:UIControlStateNormal];
    self.sexView = [HLUIHelper sexAgeIconViewWithSex:@"2" age:model.ageString];
    if (isMe){
        [self.avatarView sd_setImageWithURL:[NSURL URLWithString:model.avatar] placeholderImage:[UIImage imageNamed:@"avatar_male_placeholder"]];
        self.sexView = [HLUIHelper sexAgeIconViewWithSex:@"1" age:model.ageString];
        NSMutableArray *opuses = [NSMutableArray array];
        HLOpusModel *video = [_model videoWithUserOpuses];
        if (video){
            [opuses addObject:video];
        }
        NSArray *images = [_model imagesWithUserOpuses];
        if (images.count > 0){
            [opuses addObjectsFromArray:images];
        }
        _cycleDatas = [opuses copy];
        
    } else {
        self.cycleDatas = _model.userOpuses;
    }
    
    [self addSubview:_sexView];
    [_sexView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_nicknameLabel);
        make.left.equalTo(_nicknameLabel.mas_right).offset(6);
    }];
    
    if (_cycleDatas.count == 0){
        HLOpusModel *avatarOpus = [[HLOpusModel alloc] init];
        avatarOpus.opusType = @"1";
        avatarOpus.opusLink = model.avatar;
        self.cycleDatas = @[avatarOpus];
    }

    self.cycleScrollView.imageURLStringsGroup = [_cycleDatas qmui_mapWithBlock:^NSString * _Nonnull(HLOpusModel * _Nonnull item, NSInteger index) {
        item.isMe = isMe;
        if (item.opusLink){
            return item.opusLink;
        } else {
            return @"";
        }
        
    }];
    [self updateFollowView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notification:) name:HLUserFollowDidChangeNotification object:nil];
}

- (void)updateFollowView
{
    NSString *followType = _model.followType;
    UIColor *textColor = HLMainColor;
    NSString *title = @"关注";
    UIImage *icon = UIImageMake(@"user_detail_follow");
    
    if ([followType isEqualToString:@"0"]) {
        // 仅关注
        textColor = HLTextColor3;
        title = @"已关注";
        icon = UIImageMake(@"user_detail_unfollow");
    } else if ([followType isEqualToString:@"1"]) {
        // 已互关
        textColor = HLTextColor3;
        title = @"互相关注";
        icon = UIImageMake(@"user_detail_unfollow");
    } else if ([followType isEqualToString:@"2"]) {
        // 已拉黑
    }

    _followButton.layer.borderColor = textColor.CGColor;
    [self.followButton setTitleColor:textColor forState:UIControlStateNormal];
    [self.followButton setTitle:title forState:UIControlStateNormal];
    [self.followButton setImage:icon forState:UIControlStateNormal];
}

- (void)notification:(NSNotification *)noti
{
    NSDictionary *info = noti.object;
    NSInteger type = [[info objectForKey:@"type"] intValue];
    NSString *user = [info objectForKey:@"user"] ;
    
    if (![user isEqualToString:_model.userId]){
        return;
    }
    
    if (type ==  HLUserOptionTypeFollow){
        _model.followType = @"0";
    } else {
        _model.followType = @"1";
    }
    [self updateFollowView];
}

- (void)copyID
{
    [[UIPasteboard generalPasteboard] setString:_model.userYueId];
    [QMUITips showWithText:@"已经复制用户ID"];
}

- (void)followAction
{
    MJWeakSelf;
    BOOL hasFollow = [_model.followType isEqualToString:@"0"];
    [HLUIHelper followWithUserId:_model.userId follow:hasFollow callback:^(BOOL isConfirm) {
        if (isConfirm){
            weakSelf.model.followType = hasFollow ? @"1":@"0";
            [weakSelf updateFollowView];
        }
    }];
}

- (void)editNicknameAction
{
    MJWeakSelf
    HLEditNicknameViewController *editNicknameVC = [[HLEditNicknameViewController alloc] initWithNickname:_model.nickName callback:^(NSString * nickname) {
        if (![weakSelf.model.nickName isEqualToString:nickname]) {
            [weakSelf editInfoWithNickname:nickname];
        }
    }];
    [self.qmui_viewController.navigationController pushViewController:editNicknameVC animated:YES];
}

- (void)guardianAction
{
    [HLUIHelper h5WithURL:HLH5GuardianUrl controller:self.qmui_viewController];
}

- (void)editInfoWithNickname:(NSString *)nickname
{
    NSDictionary *params = @{@"nickName":nickname};
    HLEditInfoRequest *editRequest = [[HLEditInfoRequest alloc] initWithEditInfo:params];
    [editRequest startWithCompletionBlockWithSuccess:^(__kindof HLEditInfoRequest * _Nonnull request) {
        if (request.isSuccess){
            [QMUITips showWithText:@"修改昵称成功"];
            self.model.nickName = nickname;
            [self.nicknameLabel setText:nickname];
        }
    } failure:nil];
}

#pragma mark SDCycleScrollViewDelegate

- (Class)customCollectionViewCellClassForCycleScrollView:(SDCycleScrollView *)view
{
    return [HLCycleScrollCell class];
}

- (void)setupCustomCell:(HLCycleScrollCell *)cell forIndex:(NSInteger)index cycleScrollView:(SDCycleScrollView *)view
{
    [[NSNotificationCenter defaultCenter] postNotificationName:HLUserDetailScrollDidChangeNotification object:nil];
    cell.model = self.cycleDatas[index];
    
}

/** 点击图片回调 */
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    HLOpusModel *opusModel = self.cycleDatas[index];
    if (index == 0 && opusModel.opusLink == nil){
        return;
    }
    
    if ([opusModel.opusType isEqualToString:@"2"]){
        opusModel.isPlay = YES;
        return;
    }
    HXPhotoManager *photoManager = [HXPhotoManager managerWithType:HXPhotoManagerSelectedTypePhotoAndVideo];
    
    NSMutableArray *models = [NSMutableArray arrayWithCapacity:_cycleDatas.count];
    for (HLOpusModel *opus in _cycleDatas) {
        if ([opus.opusType isEqualToString:@"2"]){
            HXCustomAssetModel *model = [HXCustomAssetModel livePhotoAssetWithNetworkImageURL:[NSURL URLWithString:opus.videoCoverPic] networkVideoURL:[NSURL URLWithString:opus.opusLink] selected:YES];
            [models addObject:model];
        } else {
            HXCustomAssetModel *model = [HXCustomAssetModel assetWithNetworkImageURL:[NSURL URLWithString:opus.opusLink] selected:YES];
            [models addObject:model];
        }
    }
    [photoManager addCustomAssetModel:models];
    [HLPickerManager previewWithManager:photoManager index:index controller:self.qmui_viewController];
}

- (void)avatarPreview
{
    if (_model.avatar == nil){
        return;
    }
    HXPhotoManager *photoManager = [HXPhotoManager managerWithType:HXPhotoManagerSelectedTypePhotoAndVideo];
    
    HXCustomAssetModel *model = [HXCustomAssetModel assetWithNetworkImageURL:[NSURL URLWithString:_model.avatar] selected:YES];
    [photoManager addCustomAssetModel:@[model]];
    [HLPickerManager previewWithManager:photoManager index:0 controller:self.qmui_viewController];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
